<template>
  <div class="doctor">
    <Form
      :label-width="118"
      :model="formData"
      ref="formItem"
      :rules="infoRules"
    >
      <Row :gutter="48">
        <i-col :span="16">
          <FormItem label="医生姓名" prop="name" class="ivu-inline-block">
            <Input placeholder="请输入医生姓名" v-model="formData.name" />
          </FormItem>
          <FormItem label="证书编号" prop="cert_no" class="ivu-inline-block">
            <Input placeholder="请输入医生姓名" v-model="formData.cert_no" />
          </FormItem>
          <FormItem label="科室" prop="clinic_name" class="ivu-inline-block">
            <Input
              placeholder="请输入科室名称"
              v-model="formData.clinic_name"
            />
          </FormItem>
          <FormItem label="职称" prop="profession_name" class="ivu-inline-block">
            <Input placeholder="请输入" v-model="formData.profession_name" />
          </FormItem>
          <FormItem label="所属医院" prop="hospital_name" class="ivu-inline-block">
            <Input
              placeholder="请输入医院名称"
              v-model="formData.hospital_name"
            />
          </FormItem>
          <FormItem label="挂号类型" prop="register_type" class="ivu-inline-block">
            <Select label="普通号" v-model="formData.register_type">
              <Option
                v-for="(item, index) in registerType"
                :value="index"
                :key="index"
                >{{ item }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="擅长技术" prop="good_skill">
            <Input type="textarea" v-model="formData.good_skill" />
          </FormItem>
          <FormItem label="简介" prop="simple_desc">
            <Input type="textarea" v-model="formData.simple_desc" />
          </FormItem>
          <FormItem label="内容" prop="content">
            <ckeditor
              :editor="editor"
              v-model="formData.content"
              :config="editorConfig"
            ></ckeditor>
          </FormItem>
        </i-col>
        <i-col :span="8">
          <FormItem label="头像" :label-width="80" prop="avatar">
            <div v-if="formData.avatar">
              <img :src="formData.avatar" :width="100" :height="100" />
            </div>
            <div class="imageUpdate">
              <Upload
                ref="upload"
                name="file"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['jpg', 'jpeg', 'png']"
                :action="requestAction"
                :before-upload="handleBefore"
              >
                <div>
                  <Button
                    type="primary"
                    class="ivu-mr-8"
                    size="small"
                    :loading="loading"
                  >
                    {{ loading ? "上传中..." : "上传" }}
                  </Button>
                </div>
              </Upload>
              <Button type="success" size="small" @click="showImgModel = true"
                >选择</Button
              >
            </div>
          </FormItem>
        
      <FormItem label="视频ID" prop="video_id" :label-width="80">
          <Input
            placeholder="请输入视频ID,视频ID从视频后台获取"
            v-model="formData.video_id"
          />
      </FormItem>
      <FormItem label="视频封面" :label-width="80" prop="cover_img" :rules="formData.video_id?[{ required: true, message: '请选择视频封面', trigger: 'bulr' }]:infoRules.cover_img">
        <div v-if="formData.cover_img" class="demo-upload-list">
          <img :src="formData.cover_img" width="100" height="100" />
          <div class="demo-upload-list-cover">
                <Icon type="ios-trash-outline" @click="formData.cover_img=''"></Icon>
            </div>
        </div>
        <div class="imageUpdate">
          <Upload
            ref="upload"
            name="file"
            :show-upload-list="false"
            :on-success="handleSuccess1"
            :format="['jpg', 'jpeg', 'png']"
            :action="requestAction"
            :before-upload="handleBefore1"
          >
            <div>
              <Button
                type="primary"
                class="ivu-mr-8"
                size="small"
                :loading="loading1"
              >
                {{ loading1 ? "上传中..." : "上传" }}
              </Button>
            </div>
          </Upload>
          <Button type="success" size="small" @click="showImgModel1 = true"
            >选择</Button
          >
        </div>
      </FormItem>
          <FormItem label="类别" prop="type" :label-width="80">
            <RadioGroup v-model="formData.type">
              <Radio
                :label="index"
                v-for="(item, index) in doctorType"
                :key="index"
              >
                {{ item }}
              </Radio>
            </RadioGroup>
          </FormItem>
          
          <FormItem
            label="挂号费用"
            prop="register_money"
            class="ivu-inline-block"
            :label-width="80"
          >
            <InputNumber
              :style="{ width: '100%' }"
              :precision="0"
              :min="0"
              v-model="formData.register_money"
            />
          </FormItem>
          <FormItem
            label="排序"
            prop="sort"
            class="ivu-inline-block"
            :label-width="80"
          >
            <InputNumber
              :style="{ width: '100%' }"
              :precision="0"
              :min="0"
              v-model="formData.sort"
            />
          </FormItem>
          <FormItem
            label="首页推荐"
            prop="recommend_type"
            class="ivu-inline-block"
            :label-width="80"
          >
            <Switch v-model="formData.recommend_type" />
          </FormItem>
          <FormItem
            label="关注"
            prop="sub_config_num"
            class="ivu-inline-block"
            :label-width="80"
          >
            <InputNumber
              :style="{ width: '100%' }"
              :precision="0"
              :min="0"
              v-model="formData.sub_config_num"
            />
          </FormItem>
          <FormItem label="标签" prop="model1" :label-width="80">
            <Select
              v-model="formData.model1"
              filterable
              multiple
              allow-create
              @on-change="selectTag"
              @on-create="handleCreate"
            >
              <Option
                v-for="item in tagList"
                :value="+item.value"
                :key="item.value"
                :disabled="+item.disabled === 1 ? false : true"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="状态" :label-width="80">
            <RadioGroup v-model="formData.leave_type">
              <Radio
                :label="index"
                v-for="(item, index) in leaveType"
                :key="index"
                >{{ item }}</Radio
              >
            </RadioGroup>
          </FormItem>
        </i-col>
      </Row>
      <glo-check v-model="showImgModel" @getImgArr="getImgArr" />
      <glo-check v-model="showImgModel1" @getImgArr="getImgArr1" />
    </Form>
  </div>
</template>
<script>
import { addDoctor, doctorDetial, updateDoctor } from "@/api/jzy.js"
import { updatefileTemp } from '@/api/set.js'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import CKEditor from '@ckeditor/ckeditor5-vue'
const ckUpload = require("../../../libs/ckeditorUplodImg5")
import Setting from '@/setting'
import util from '@/libs/util'
import { computed } from '@vue/runtime-core'
export default {
  name: 'modalName',
  components: { ckeditor: CKEditor.component },
  props: ['doctorInfo', 'editorType','articleModal'],
  data () {
    return {
      loading: false,
      loading1: false,
      showImgModel: false,
      showImgModel1: false,
      baseUrl: Setting.request.apiBaseURL,
      requestAction: '',
      editor: ClassicEditor,
      editorConfig: {
        extraPlugins: [ckUpload.MyCustomUploadAdapterPlugin],
        fullscreen: {
          // 点击按钮后会执行的回调函数
          handler: () => {
            // this.modalstatus = true;
          }
        },
        material: {
          // 点击按钮后会执行的回调函数
          handler: () => {
            this.askData()
            this.modalstatus = true
            this.showlink = true
            this.img = ''
            this.isDobule = true
          }
        },
        mediaEmbed: {
            providers: [{
            name: 'myprovider',
            url: [
              /^lizzy.*\.com.*\/media\/(\w+)/,
              /^www\.lizzy.*/,
              /^.*/
            ],
            html: match => {
              //获取媒体url
              const input = match['input'];
            //console.log('input' + match['input']);
              return (
                '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 70%;">' +
                  `<iframe src="${input}" ` +
                    'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' +
                    'frameborder="0" allowtransparency="true" allow="encrypted-media">' +
                  '</iframe>' +
                '</div>'
              );
            }
          }]
        }
      },
      model1: [],
      formData: {
        name: '',
        cert_no: '',
        avatar: '',
        hospital_name: '',
        clinic_name: '',
        profession_name: '',
        good_skill: '',
        simple_desc: '',
        content: '',
        type: '1',
        register_type: '1',
        register_money: 0,
        sort: '',
        sub_config_num: '',
        recommend_type: false,
        model1: [],
        tag: [],
        leave_type: '1',
        cover_img:'',
        video_id:''
      },
      infoRules: {
        name: [
          { required: true, message: "请输入医生姓名", trigger: "bulr" },
          { trigger: "bulr", validator: this.watermarkContentVaild }
        ],
        cert_no: [{ required: true, message: "请输入证书编号", trigger: "bulr" }],
        avatar: [{ required: true, message: "请上传头像", trigger: "bulr" }],
        hospital_name: [{ required: true, message: "请输入所属医院", trigger: "bulr" }],
        clinic_name: [{ required: true, message: "请输入科室", trigger: "bulr" }],
        profession_name: [{ required: true, message: "请输入职称", trigger: "bulr" }],
        good_skill: [{ required: true, message: "请输入擅长技术", trigger: "bulr" }],
        content: [{ required: true, message: "请输入内容", trigger: "bulr" }],
        cover_img:[{ required: false, trigger: "bulr" }],
      },
      doctorType: {},
      leaveType: {},
      registerType: {},
      initTagList: [],
      tagList: [],
    }
  },
  methods: {
    watermarkContentVaild (rule, value, callback) {
      let length = value.replace(/[^\x00-\xff]/g, '01').length
      if (length > 10) {
        callback(new Error("请输入1~5个汉字"))
      } else {
        callback()
      }
    },
    handleBefore () {
      this.loading = true
    },
    handleSuccess (response, file, fileList) {
      this.formData.avatar = `${response.data.host}${response.data.image_url[0]}`
      this.loading = false
      const id = response.data.image_id[0]
      updatefileTemp({ id })
    },
    handleBefore1 () {
      this.loading1 = true
    },
    handleSuccess1 (response, file, fileList) {
      this.formData.cover_img = `${response.data.host}${response.data.image_url[0]}`
      this.loading1 = false
      const id = response.data.image_id[0]
      updatefileTemp({ id })
    },
    getImgArr (arr) {
      this.formData.avatar = arr[0]
    },
    getImgArr1 (arr) {
      this.formData.cover_img = arr[0]
    },
    handleCreate (e) {
      if(e.trim().length<1){
        this.$Message['warning']('标签不能为空')
        return
      }else if (e.length > 6) {
        this.$Message['warning']('标签长度不能超过6')
        return
      } else {
        let add=true
        this.tagList.forEach(item=>{
          if(item.label==e){
            add=false
            return;
          }
        })
        if(add){
          var id=new Date().getTime()      
          this.tagList.push({
            value: id,
            label: e,
            disabled: '1',
          })  
        }
         
      }
    },
    selectTag (e) {
      this.tagList.forEach(item=>{
        if(e[e.length - 1]==item.label){            
         if(e.includes(+item.value)){
           e.pop()
         }else{
           e[e.length - 1]=+item.value
         }
        }
      })
      if (e.length && (e[e.length - 1].length > 6||e[e.length - 1].toString().trim().length<1)) {
        e.pop()
        return
      }
      if (e.length > 3) {
        this.$Message.warning("标签不能超过三个~")
        e.splice(3, 1)
        return
      }
    },
    saveData () {
      this.$refs['formItem'].validate((valid) => {
        if (valid) {
          this.formData.tag = []
          this.formData.model1.forEach((item) => {
            let flag = true,add=true
            this.initTagList.forEach(ele => {
              if (+ele.value == +item) {
                this.formData.tag.push({ id: item, name: ele.label })
                flag = false
                add=false
              }
            })
            if (flag) {
              this.tagList.forEach(ele => {
                if (+ele.value == +item) {
                  this.formData.tag.push({ id: 0, name: ele.label })
                  flag = true
                   add=false
                }
              })
              if(add){
                this.formData.tag.push({ id: 0, name: item })
              }
              
            }
          })
          let params={...this.formData }
          params.recommend_type=params.recommend_type?'1':'2'
          if (this.editorType) {
            addDoctor(params).then(res => {
              this.$emit('refresh', false)
            })
          } else {
            params.id = this.doctorInfo.id
            updateDoctor(params).then(res => {
              this.$emit('refresh', false)
            })
          }
          doctorDetial({ id: '0' }).then((res) => {
            this.initTagList = [...res.condition.tag]
            this.tagList = res.condition.tag
          })
        }
      })


    }
  },
  watch: {
    articleModal () {
      if (this.editorType) {
        this.formData = {
          name: '',
          cert_no: '',
          avatar: '',
          hospital_name: '',
          clinic_name: '',
          profession_name: '',
          good_skill: '',
          simple_desc: '',
          content: '',
          type: '1',
          register_type: '1',
          register_money: 0,
          sort: '',
          sub_config_num: '',
          recommend_type: false,
          model1: [],
          tag: [],
          cover_img:'',
          video_id:'',
          leave_type: '1'
        }
        this.$refs['formItem'].resetFields()
        doctorDetial({ id: 0 }).then(res => {
          this.doctorType = res.condition.type
          this.registerType = res.condition.register_type
          this.leaveType = res.condition.leave_type

          this.initTagList = [...res.condition.tag]
          this.tagList = res.condition.tag
        })
      } else {
        doctorDetial({ id: this.doctorInfo.id }).then(res => {
          this.doctorType = res.condition.type
          this.registerType = res.condition.register_type
          this.leaveType = res.condition.leave_type
          this.initTagList = [...res.condition.tag]
          this.tagList = res.condition.tag
          this.formData = {
            name: res.name,
            cert_no: res.cert_no,
            avatar: res.avatar,
            hospital_name: res.hospital_name,
            clinic_name: res.clinic_name,
            profession_name: res.profession_name,
            good_skill: res.good_skill,
            simple_desc: res.simple_desc,
            content: res.content,
            type: res.type + '',
            register_type: res.register_type + '',
            register_money: res.register_money,
            sort: res.sort,
            sub_config_num: res.sub_config_num,
            recommend_type: res.recommend_type == 1 ? true : false,
            leave_type: res.leave_type + '',
            model1: res.tag_ids,
            cover_img:res.cover_img,
            video_id:res.video_id,
            tag: []
          }          
        })
      }
    }
  },
  mounted () {
    this.requestAction = this.baseUrl + `/v1/upload/images?auth_access_token=${util.cookies.get('token')}&auth_project_id=${localStorage.getItem('currentProject')}`
  }
}
</script>
<style lang='less' scoped>
.ivu-modal {
  top: 30px;
}
.imageUpdate {
  display: flex;
}
.imageUpdate button {
  vertical-align: top;
}
.ivu-form-item {
  margin-bottom: 20px;
}
.doctor{
  padding-bottom: 20px;
}
.doctor .ivu-inline-block {
  width: 50%;
}
/deep/.ck.ck-editor__main > .ck-editor__editable {
  height: 260px;
}
.demo-upload-list{
    display: inline-block;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
}
.demo-upload-list img{
    width: 100%;
    height: 100%;
}
.demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
}
.demo-upload-list:hover .demo-upload-list-cover{
    display: block;
}
.demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
}
</style>
